import { CheckCircleFilled, CloseCircleFilled, PlusOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Badge, Button, Popconfirm, Tag } from 'antd';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import Form from './components/Form';
import FormCopy from './components/CopyForm';

import * as c from '@/services/consts';
import * as api from '@/services/nodeTemplate';


const NodeList: React.FC = () => {

  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [formCopyVisible, setFormCopyVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.NodeTemplate | undefined>(
    undefined,
  );

  // const [productId, setProductId] = useState<string | undefined>(undefined);

  const actionRef = useRef<ActionType>();

  const { hasRight } = useModel('useAuthModel');

  // const { getProduct, getProductMenuItems } = useModel(
  //   'useGlobalModel',
  //   (model) => ({
  //     getProduct: model.getProduct,
  //     getProductMenuItems: model.getProductMenuItems,
  //   }),
  // );

  // const productMenuItems = getProductMenuItems(true);
  

  const loadData = async (
    params?: { [key: string]: any },
    sorter?: { [key: string]: any },
    filter?: { [key: string]: any },) => {

    const result = await api.list(params, sorter, filter);
    return result;
  };

  const handleFormSubmit = async (record: API.NodeTemplate) => {
    console.log(record);
    // return;

    let result: API.Result;
    if (current) {
      result = await api.update({
        ...current,
        ...record,
      });
    } else {
      result = await api.add({ ...record });
    }

    if (result && result.success === true) {
      setCurrent(undefined);
      setFormVisible(false);
      actionRef.current?.reload();
    }
  };

  const handleRemove = async (id: number) => {
    const result = await api.remove({ key: id });
    if (result.success) {
      actionRef.current?.reload();
    }
  };
  
  const handleCopySubmit = async (name: string, remark?: string) => {
    let result: API.Result;
    result = await api.copy({ id: current.id, name: name, remark: remark });

    if (result && result.success === true) {
      setFormCopyVisible(false);
      actionRef.current?.reload();
    }
  };


  let columns: ProColumns<API.NodeTemplate>[] = [
    {
      title: '模板ID',
      align: 'center',
      width: 100,
      dataIndex: 'id',
      sorter: true,
    },
    // {
    //   title: '产品',
    //   align: 'center',
    //   width: 100,
    //   dataIndex: 'productId',
    //   sorter: true,
    //   renderText: (_, record) => {
    //     if (record.productId) {
    //       const product = getProduct(record.productId);
    //       if (product) {
    //         return product.name;
    //       }
    //     }
    //     return '';
    //   },
    // },
    // {
    //   title: 'Http',
    //   align: 'center',
    //   width: 80,
    //   dataIndex: 'serverHttpConfig',
    //   search: false,
    //   renderText: (val) => {
    //     return val ? (
    //       <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
    //     ) : (
    //       <Badge count={<CloseCircleFilled style={{ color: 'orange' }} />} />
    //     );
    //   },
    // },
    // {
    //   title: 'Https',
    //   align: 'center',
    //   width: 80,
    //   dataIndex: 'serverTcpTlsConfig',
    //   search: false,
    //   renderText: (val) => {
    //     return val ? (
    //       <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
    //     ) : (
    //       <Badge count={<CloseCircleFilled style={{ color: 'orange' }} />} />
    //     );
    //   },
    // },
    // {
    //   title: 'Vision',
    //   align: 'center',
    //   width: 80,
    //   dataIndex: 'serverVisionConfig',
    //   search: false,
    //   renderText: (val) => {
    //     return val ? (
    //       <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
    //     ) : (
    //       <Badge count={<CloseCircleFilled style={{ color: 'orange' }} />} />
    //     );
    //   },
    // },
    // {
    //   title: 'Reality',
    //   align: 'center',
    //   width: 80,
    //   dataIndex: 'serverRealityConfig',
    //   search: false,
    //   renderText: (val) => {
    //     return val ? (
    //       <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
    //     ) : (
    //       <Badge count={<CloseCircleFilled style={{ color: 'orange' }} />} />
    //     );
    //   },
    // },
    // {
    //   title: '类型',
    //   align: 'center',
    //   width: 100,
    //   dataIndex: 'serverRealityConfig',
    //   search: false,
    //   renderText: (_, record) => {
    //     return record.serverHttpConfig ? <Tag color="blue">Http</Tag> 
    //       : record.serverTcpTlsConfig ? <Tag color="blue">Https</Tag>
    //       : record.serverVisionConfig ? <Tag color="blue">Vision</Tag>
    //       : record.serverRealityConfig ? <Tag color="blue">Reality</Tag>
    //       : '';
    //   },
    // },
    {
      title: '名称',
      dataIndex: 'name',
      sorter: true,
    },
    {
      title: '国家地区',
      // align: 'center',
      // width: 160,
      dataIndex: 'areas',
      sorter: true,
      renderText: (val) => {
        return val ? val[0] : '';
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 120,
      render: (_, record) => {
        let cmps = [];
        if (hasRight('nodetemplate_create')) {
          cmps.push(
            <a
              key="copy"
              onClick={(e) => {
                setFormCopyVisible(true);
                setCurrent(record);
              }}
            >
              复制
            </a>,
          );
        }

        if (hasRight('nodetemplate_update')) {
          cmps.push(
            <a
              key="edit"
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(record);
              }}
            >
              编辑
            </a>,
          );
        }

        if (hasRight('nodetemplate_delete')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        search={false}
        pagination={false}
        // toolbar={{
        //   menu: {
        //     type: 'tab',
        //     activeKey: productId,
        //     items: productMenuItems,
        //     onChange: (tabKey) => {
        //       //console.log('tabKey', tabKey);
        //       setProductId(tabKey as string);
        //     },
        //   },
        // }}
        toolBarRender={() => {
          var toolbarDoms: any[] = [];
          if (hasRight('nodetemplate_create')) {
            toolbarDoms.push([
              <Button
                type="primary"
                key="create"
                onClick={() => {
                  setFormVisible(true);
                }}
              >
                <PlusOutlined /> 新建
              </Button>,
            ]);
          }
          return toolbarDoms;
        }}
        columns={columns}
        params={{
          // type:type,
          // productId:
          //   productId && productId !== c.DefaultOptionAll.key
          //     ? parseInt(productId)
          //     : undefined,
        }}
        request={loadData}
      />
      <Form
        visible={formVisible}
        // defaultProductId={
        //   productId && productId !== c.DefaultOptionAll.key
        //     ? parseInt(productId)
        //     : undefined
        // }
        current={current}
        onSubmit={handleFormSubmit}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
        }}
      />
      <FormCopy
        visible={formCopyVisible}
        onSubmit={handleCopySubmit}
        onCancel={() => {
          setFormCopyVisible(false);
          setCurrent(undefined);
        }}
      />
    </PageContainer>
  );
};

export default NodeList;
